package net.yebaihe.wc;

import java.util.HashMap;

import net.yebaihe.sdk.HttpConnection;
import net.yebaihe.wc.DataMan.MSGTYPE;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Application;
import android.content.Context;
import android.content.DialogInterface;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.telephony.TelephonyManager;
import android.telephony.gsm.GsmCellLocation;
import android.util.Log;
import android.widget.Toast;

public class WCApp extends Application implements StateMachineInterface{
	public String email="";
	public String city="杭州";
	public String cellcity="";
	
	public double celllon=-1;
	public double celllat=-1;
	public double gpslon=-1;
	public double gpslat=-1;
	public boolean alertedCityChange=false;
	
	public boolean inited=false;
	private Handler cellHandler=new Handler(){
    	public void handleMessage(Message message) {
    		String city="";
    		switch (message.what) {
    		case HttpConnection.DID_START:
    			break;
    		case HttpConnection.DID_SUCCEED: {
    			String body=message.obj.toString();
    			try {
					JSONObject data = new JSONObject(body);
					if (data.has("location")){
						city=data.getJSONObject("location").getJSONObject("address").getString("city");
		    			Log.d("", city);
		    			celllon=data.getJSONObject("location").getDouble("longitude");
		    			celllat=data.getJSONObject("location").getDouble("latitude");
		    			updateMyLocation();
						if (city.length()>0){
							if (city.endsWith("市")){
								city=city.substring(0,city.length()-1);
				    			//Toast.makeText(WCApp.this, "您当前所在的城市是："+city, Toast.LENGTH_LONG).show();
							}
							cellcity=city;
							if (!alertedCityChange){
								checkCityChange();
							}
						}
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
        		if (city.length()<=0){
            		Toast.makeText(WCApp.this, "基站定位失败，请确认您存在有效的数据网络连接！", Toast.LENGTH_LONG).show();
        		}
        		gpslocation();
                break;
    		}
    		case HttpConnection.DID_PROGRESS:{
    			break;
    		}
    		case HttpConnection.DID_ERROR:
        		Toast.makeText(WCApp.this, "基站定位失败，请确认您存在有效的数据网络连接！", Toast.LENGTH_LONG).show();
        		gpslocation();
    			break;
    		}
    	}
	};
	private LocationListener locationListener=new LocationListener(){

		@Override
		public void onLocationChanged(Location location) {
			gpslon=location.getLongitude();
			gpslat=location.getLatitude();
			updateMyLocation();
			LocationManager alm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
			alm.removeUpdates(locationListener);
            Toast.makeText(WCApp.this, "GPS定位成功", Toast.LENGTH_SHORT).show();
		}

		@Override
		public void onProviderDisabled(String provider) {
			Toast.makeText(WCApp.this, "GPS定位已被禁止", Toast.LENGTH_SHORT);
		}

		@Override
		public void onProviderEnabled(String provider) {
			Toast.makeText(WCApp.this, "GPS定位已被开启", Toast.LENGTH_SHORT);
		}

		@Override
		public void onStatusChanged(String provider, int status, Bundle extras) {
		}
		
	};
	protected int sessionid=-1;
	protected long restaurant=-1;
	public int notifications=0;
	public Activity curStateMachine;
	public String otherRestaurantSql="";
	protected long zone=-1;
	protected long pendingOrder=-1;
	protected boolean inviteInFriends=false;
	
	public void updateSelfLocation() {
		try {
			cellLocation();
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}

	public void checkCityChange() {
		if (!cellcity.equals(WCApp.this.city)){
			doAlertCityChange();
		}
	}

	protected void doAlertCityChange() {
		if (curStateMachine!=null)
		new AlertDialog.Builder(curStateMachine).setTitle("城市变更")
			.setMessage("检测到您现在所在的城市是："+this.cellcity+"，您要切换到这个城市吗？")
			.setPositiveButton("是的", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface arg0, int arg1) {
					city=cellcity;
					if (curStateMachine!=null){
						Pref.get(curStateMachine).save("city", city);
						StateMachineInterface machine=(StateMachineInterface)curStateMachine;
						machine.HandleMessage(MSGTYPE.CITY_CHANGE, true, null);
					}
				}
			})
			.setNegativeButton("不用", null).create().show();
	}

	public void updateMyLocation() { 
		if (email.length()>0){
			if (gpslon!=-1){
				DataMan.get(this).updateMyLocation(email,gpslon,gpslat);
				//Toast.makeText(this, "已按照GPS坐标更新位置", Toast.LENGTH_SHORT).show();
			}
			else if (celllon!=-1){
				//Toast.makeText(this, "已按照基站坐标更新位置", Toast.LENGTH_SHORT).show();
				DataMan.get(this).updateMyLocation(email,celllon,celllat);
			}
		}
	}

	protected void gpslocation() {
		LocationManager alm = (LocationManager) this
                .getSystemService(Context.LOCATION_SERVICE);
        if (alm
                .isProviderEnabled(android.location.LocationManager.GPS_PROVIDER)) {
            // 查找到服务信息
            Criteria criteria = new Criteria();
            criteria.setAccuracy(Criteria.ACCURACY_FINE); // 高精度
            criteria.setAltitudeRequired(false);
            criteria.setBearingRequired(false);
            criteria.setCostAllowed(true);
            criteria.setPowerRequirement(Criteria.POWER_LOW); // 低功耗

            String provider = alm.getBestProvider(criteria, true); // 获取GPS信息
            alm.requestLocationUpdates(provider, 100 * 1000, 500,
                    locationListener);        
    		//Toast.makeText(this, "正在进行GPS定位，可能会持续一段时间...", Toast.LENGTH_SHORT).show();
        }
	}

	private void cellLocation() throws JSONException {
		//Toast.makeText(this, "正在进行基站定位...", Toast.LENGTH_SHORT).show();

		TelephonyManager tm = (TelephonyManager) this
				.getSystemService(Context.TELEPHONY_SERVICE);
		GsmCellLocation gcl = (GsmCellLocation) tm.getCellLocation();
		if (gcl==null){
			Toast.makeText(this, "基站定位目前仅支持GSM网络，抱歉", Toast.LENGTH_SHORT).show();
			return;
		}
		int cid = gcl.getCid();
		int lac = gcl.getLac();

		int mcc = Integer.valueOf(tm.getNetworkOperator().substring(0,
				3));
		int mnc = Integer.valueOf(tm.getNetworkOperator().substring(3,
				5));
			//组装JSON查询字符串
			JSONObject holder = new JSONObject();
			holder.put("version", "1.1.0");
			holder.put("host", "maps.google.com");
			holder.put("address_language", "zh_CN");
			holder.put("request_address", true);

			JSONArray array = new JSONArray();
			JSONObject data = new JSONObject();
			data.put("cell_id", cid); // 25070
			data.put("location_area_code", lac);// 4474
			data.put("mobile_country_code", mcc);// 460
			data.put("mobile_network_code", mnc);// 0
			array.put(data);
			holder.put("cell_towers", array);
			Log.d("", holder.toString());
			new HttpConnection(this,cellHandler).post("http://www.google.com/loc/json", holder.toString());
	}

    private double deg2rad(double deg) {
    	return (deg * Math.PI / 180.0);
    }

    private double rad2deg(double rad) {
    	return (rad * 180.0 / Math.PI);
    }
	public double distance(double lat1, double lon1, double lat2, double lon2, char unit) {
    	double theta = lon1 - lon2;
    	double dist = Math.sin(deg2rad(lat1)) * Math.sin(deg2rad(lat2)) + Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) * Math.cos(deg2rad(theta));
    	dist = Math.acos(dist);
    	dist = rad2deg(dist);
    	dist = dist * 60 * 1.1515;
    	if (unit == 'K') {
    		dist = dist * 1.609344;
    	} else if (unit == 'N') {
    		dist = dist * 0.8684;
    	}
    	return (dist);
    }

	
	public double getBestLon(){
		if (gpslon!=-1) return gpslon;
		return celllon;
	}
	
	public double getBestLat(){
		if (gpslat!=-1) return gpslat;
		return celllat;
	}
	
	@Override
	public void HandleMessage(MSGTYPE register, boolean ret,
			HashMap<String, String> params) {
		// TODO Auto-generated method stub
		
	}

	public void init() {
		if (inited) return;
		inited=true;
		email=Pref.get(this).read("email","");
		if (MyHelper.get(this).getCurrUserInfoData(email)==null){
			email="";
		}
		city=Pref.get(this).read("city", "杭州");
		DataMan.get(this);//init offline data
		this.updateSelfLocation();
	}
}
